export const DomUtil = {
  /**
   * @param {string} val
   * @returns {string}
   */
  html2Text (val) {
    const div = document.createElement('div')
    div.innerHTML = val
    return div.textContent || div.innerText
  },
  /**
   * @param {HTMLElement} element
   * @param {string} className
   */
  toggleClass (element, className) {
    if (!element || !className) {
      return
    }
    let classString = element.className
    const nameIndex = classString.indexOf(className)
    if (nameIndex === -1) {
      classString += '' + className
    } else {
      classString =
        classString.substr(0, nameIndex) +
        classString.substr(nameIndex + className.length)
    }
    element.className = classString
  },
  /**
   * Check if an element has a class
   * @param {HTMLElement} elm
   * @param {string} cls
   * @returns {boolean}
   */
  hasClass (ele, cls) {
    return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  },

  /**
   * Add class to element
   * @param {HTMLElement} elm
   * @param {string} cls
   */
  addClass (ele, cls) {
    if (!this.hasClass(ele, cls)) ele.className += ' ' + cls
  },

  /**
   * Remove class from element
   * @param {HTMLElement} elm
   * @param {string} cls
   */
  removeClass (ele, cls) {
    if (this.hasClass(ele, cls)) {
      const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
      ele.className = ele.className.replace(reg, ' ')
    }
  },
  /**
   * 加载iframe
   * @param iframe
   * @param callback
   */
  load (iframe) {
    return new Promise((resolve, reject) => {
      if (iframe) {
        if (iframe.attachEvent) {
          iframe.attachEvent('onload', function () {
            resolve()
          })
        } else {
          iframe.onload = function () {
            resolve()
          }
        }
      }
    })
  },
  /**
   * 转化颜色
   * @param color, 如值为：rgba(194, 78, 78, 1) 转化为： #c24e4e
   */
  getHexColor (color) {
    const values = color
      .replace(/rgba?\(/, '')
      .replace(/\)/, '')
      .replace(/[\s+]/g, '')
      .split(',')
    const a = parseFloat(values[3] || 1)
      const r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255)
      const g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255)
      const b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255)
    return '#' +
      ('0' + r.toString(16)).slice(-2) +
      ('0' + g.toString(16)).slice(-2) +
      ('0' + b.toString(16)).slice(-2)
  },
  /**
   * 设置样式变量
   * @param variableName 变量名
   * @param val 变量值
   */
  setStyleVariables (variableName, val) {
    document.getElementsByTagName('body')[0].style.setProperty(variableName, val)
  },
  /**
   * el-form validator验证不同过时，将焦点定位到第一个错误项
   */
  focusError () {
    if (document.querySelector('.el-form-item__error')) {
      document.querySelector('.el-form-item__error').parentNode.scrollIntoView({
          block: 'start',
          behavior: 'smooth'
      })
    }
  }

}
